using System;
using System.Collections.Generic;
using MSOffice = Microsoft.Office.Core;
using MSOutlook = Microsoft.Office.Interop.Outlook;

namespace Microsoft.Sample.Outlook.Utility
{
	public class ToolbarComboBoxEventArgs : CommandBarEventArgs
	{
		private int _index;
		public int Index
		{
			get { return _index;}
		}
	
		internal ToolbarComboBoxEventArgs(WindowAdapter window, MSOffice.CommandBar bar, int index)
			: base(window, bar)
		{
			_index = index;
		}
	}

    public sealed class ToolbarComboBox : ToolbarControl
	{
		private MSOffice.MsoComboStyle _style = MSOffice.MsoComboStyle.msoComboNormal;
		private List<string> _items = new List<string>();
		private int _dropDownLines = 0;

		public MSOffice.MsoComboStyle Style
		{
			get { return _style; }
			set { _style = value; }
		}

		public int DropDownLines
		{
			get { return _dropDownLines; }
			set { _dropDownLines = value; }
		}
	
		public IList<string> Items
		{
			get { return _items; }
		}

		public event EventHandler<ToolbarComboBoxEventArgs> Change;

		public ToolbarComboBox(string ID)
			: base(ID)
		{
		}

		public ToolbarComboBox(string ID, MSOffice.MsoComboStyle style)
			: base(ID)
		{
			_style = style;
		}

		public ToolbarComboBox(string ID, string caption, MSOffice.MsoComboStyle style)
			: base(ID, caption)
		{
			_style = style;
		}

		public ToolbarComboBox(string ID, string caption, string tooltip, MSOffice.MsoComboStyle style)
			: base(ID, caption, tooltip)
		{
			_style = style;
		}


		internal override void Attach(MSOffice.CommandBar bar, WindowAdapter window)
		{
			MSOffice.CommandBarComboBox cbo = FindControl<MSOffice.CommandBarComboBox>(bar);

			if (cbo == null)
			{
				cbo = (MSOffice.CommandBarComboBox)bar.Controls.Add(
					MSOffice.MsoControlType.msoControlComboBox,
					Type.Missing, Type.Missing,
					this.Position != null ? this.Position.Value : Type.Missing, true);

				cbo.Parameter = this.ID;
				cbo.Tag = Guid.NewGuid().ToString();
			}

			cbo.Caption = this.Caption;
			cbo.TooltipText = this.ToolTip;
			cbo.Style = this.Style;
			cbo.DropDownLines = DropDownLines;

			foreach (string s in _items)
				cbo.AddItem(s, Type.Missing);

			cbo.Change += delegate(MSOffice.CommandBarComboBox ctrl)
			{
				ToolbarComboBoxEventArgs args = new ToolbarComboBoxEventArgs(window, bar, ctrl.ListIndex - 1);
                //Use CommandBarManager's DynamicInvoke to ensure this event fires on the right thread
                CommandBarManager.DynamicInvoke(Change, this, args);
			};

			AddControl((MSOffice.CommandBarControl)cbo);
			window.Close += delegate(object sender, EventArgs args)
			{
				RemoveControl((MSOffice.CommandBarControl)cbo);
			};
		}
	}
}
